package com.ruanhb.wsp.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.*;

/**
 * Created by r on 2018-8-30
 */
@Slf4j
public class FileUtil {
    /**
     * 读取文件
     *
     * @param file
     * @param encoding
     * @return
     * @throws IOException
     */
    public static String readFile(File file, String encoding) throws IOException {

        FileInputStream fs = null ;
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        try {
            fs = new FileInputStream(file);
            if (StringUtils.isEmpty(encoding))
                isr = new InputStreamReader(fs);
            else
                isr = new InputStreamReader(fs, encoding);
            br = new BufferedReader(isr);
            String line = null;
            Long start = System.currentTimeMillis();
            while ( (line = br.readLine()) != null){
                sb.append(line);
            }
            log.error("耗时【{}】毫秒",System.currentTimeMillis()-start);

        } finally {
            if (fs!=null)
                fs.close();
            if (isr!=null)
                isr.close();
            if (br!=null)
                br.close();
        }

        return sb.toString();

    }
}
